/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState, useCallback, useRef } from 'react';
import { connect } from 'dva';
import { Form, Modal, Row, Col, Cascader, Radio, Select } from 'antd';
import { debounce } from 'lodash';

const FormItem = Form.Item;
const { Option } = Select;

const filter = (inputValue, path) =>
  path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);

const AllotPop = ({
  form: { getFieldDecorator, validateFields, setFieldsValue },
  record = {},
  onVisible = () => {},
  getList = () => {},
  id = [],
  dispatch,
  courierList = [],
  visible,
  isZyAccount,
  branchId,
  ...reset
}) => {
  const { shipping_area_id = 0 } = record;

  // 默认为快宝驿站
  const [radioValue, setRadioValue] = useState(shipping_area_id * 1 || 0);
  const [courierId, setCourierId] = useState(null);
  const [stationList, setStationList] = useState([]);
  const [page, setPage] = useState(1);
  const counter = useRef(1);

  const onRadioChange = e => {
    setRadioValue(e.target.value);
    counter.current = 1;
    if (e.target.value === 0) {
      setFieldsValue({
        courier_id: [],
      });
    } else {
      setFieldsValue({
        courier_id: undefined,
      });
    }
  };

  const onOk = useCallback(
    () => {
      validateFields((err, data) => {
        if (err) return;
        dispatch({
          type: 'orderDetails/dispatchOrder',
          payload: {
            order_id: id.join(','),
            courier_id: radioValue == 0 ? courierId : data.courier_id,
          },
        }).then(() => {
          getList();
          onVisible(false);
        });
      });
    },
    [onVisible, validateFields, dispatch, id, courierId, getList, radioValue],
  );

  // 设置业务员的id
  const onCascaderChange = (_, selectedOptions) => {
    if (selectedOptions.length > 0) {
      setCourierId(selectedOptions[1].kdy_id);
    }
  };

  const displayRender = label => label[1];

  const getStationList = useCallback(
    ({ keyword, currentPage = 1 } = {}) => {
      if (isZyAccount) {
        return dispatch({
          type: 'area/zyGetSubPostStations',
          payload: {
            page: currentPage,
            status: 1,
            keyword,
            branch_id: branchId,
            pageSize: 20,
          },
        });
      }
      return dispatch({
        type: 'area/subList',
        payload: {
          is_district: '0',
          key: '1',
          keyword,
          pageNum: currentPage,
        },
      });
    },
    [branchId, dispatch, isZyAccount],
  );

  const onPopupScroll = useCallback(
    e => {
      e.persist();
      const { target } = e;
      if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
        counter.current += 1;
        if (counter.current > page + 1) return;

        getStationList({ currentPage: counter.current }).then(res => {
          const { list = [], paginations = {} } = res;
          if (list.length == 0) return;
          setStationList(prevState => {
            prevState.push(...list);
            return prevState;
          });
          setPage(paginations.page * 1);
        });
      }
    },
    [getStationList, page],
  );

  const onSearch = debounce(
    value => {
      if (value) {
        getStationList({ keyword: value }).then(res => {
          const { list = [] } = res || {};
          if (list.length == 0) return;
          setStationList(list);
        });
      }
    },
    300,
    { leading: false, trailing: true },
  );

  useEffect(
    () => {
      if (visible && radioValue === 2) {
        getStationList().then(res => {
          const { list = [] } = res;
          setStationList(list);
        });
      } else {
        setPage(1);
        counter.current = 1;
      }
    },
    [visible, dispatch, getStationList, radioValue],
  );

  return (
    <Modal
      width={600}
      title="订单分配"
      onOk={onOk}
      onCancel={() => onVisible(false)}
      destroyOnClose
      visible={visible}
      {...reset}
      style={{ paddingBottom: 300 }}
    >
      <Form>
        <Row type="flex" justify="space-between" align="middle">
          <Col span={8}>
            <div style={{ fontSize: 20, fontWeight: 'bold' }}>分配订单给</div>
          </Col>
          <Col span={16}>
            <Radio.Group onChange={onRadioChange} value={radioValue}>
              <Radio value={0}>业务员</Radio>
              <Radio value={2}>快宝驿站</Radio>
            </Radio.Group>
          </Col>
        </Row>
        <Row type="flex" justify="center" align="middle">
          <Col span={8}>
            <FormItem style={{ fontSize: 20, fontWeight: 'bold' }}>
              {radioValue === 0 ? '业务员' : '快宝驿站'}
            </FormItem>
          </Col>
          <Col span={16}>
            <FormItem>
              {getFieldDecorator('courier_id', {
                // initialValue: [record.company_site_id, record.collect_courier_mobile],
                rules: [
                  {
                    required: true,
                    message: '请选择需要分配的对象',
                  },
                ],
              })(
                radioValue == 0 ? (
                  <Cascader
                    expandTrigger="click"
                    options={courierList}
                    displayRender={displayRender}
                    placeholder="可根据业务员手机、姓名搜索"
                    showSearch={{ filter }}
                    onChange={onCascaderChange}
                  />
                ) : (
                  <Select
                    showSearch
                    placeholder="请选择驿站"
                    onPopupScroll={onPopupScroll}
                    onSearch={onSearch}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {stationList.map(({ inn_name, cm_id }) => (
                      <Option key={cm_id} value={cm_id}>
                        {inn_name}
                      </Option>
                    ))}
                  </Select>
                ),
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default connect(({ area }) => ({
  stationList: area.subordinates.list || [],
}))(Form.create()(AllotPop));
